﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Common.Extensions
{
    public static class FormFileStreamExtensions
    {
        // 转换为 MemoryStream
        public static async Task<MemoryStream> ToMemoryStreamAsync(this IFormFile file)
        {
            var memoryStream = new MemoryStream();
            await file.CopyToAsync(memoryStream);
            memoryStream.Position = 0;
            return memoryStream;
        }

        // 转换为字节数组
        public static async Task<byte[]> ToByteArrayAsync(this IFormFile file)
        {
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);
                return memoryStream.ToArray();
            }
        }

        // 保存到指定路径
        public static async Task SaveToFileAsync(this IFormFile file, string filePath)
        {
            // 确保目录存在
            var directory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }

        // 计算文件哈希
        public static async Task<string> CalculateHashAsync(this IFormFile file)
        {
            using (var stream = file.OpenReadStream())
            using (var sha256 = System.Security.Cryptography.SHA256.Create())
            {
                var hashBytes = await sha256.ComputeHashAsync(stream);
                return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            }
        }
    }
}
